package com.my.app.document.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.my.model.Request;
import com.my.toolkit.JsonUtil;
import com.my.utils.ClassUtil;

import lombok.Data;

@Data
public class ApiInfo {

	private String[] parentPath;//上级路径
	private String[] path;// 访问路径
	private String description;// 描述
	private String[] contentType;// 内容类型
	private RequestMethod[] requestMethod;// 可接受的方法类型
	private List<ApiParameter> params;// 参数列表
	private ApiResult result;
	private String name;
	private String fullName;
	private String simpleName;
	private String methodName;
	private boolean requestBody;
	
	
	public String getUrl() {
		String parent="";
		if(parentPath!=null&&parentPath.length>0) {
			parent=parentPath[0];
		}
		return parent+path[0];
	}
	
	public String getContentType() {
		return toString(contentType);
	}
	
	
	public String getRequestMethod() {
		if(requestMethod==null||requestMethod.length==0) {
			return "ALL";
		}
		StringBuilder sb=new StringBuilder();
		for(RequestMethod m:requestMethod) {
			sb.append(m.toString()+",");
		}
		return sb.substring(0,sb.length()-1);
	}
	
	private String toString(String[] str) {
		if(str==null||str.length==0) {
			return "";
		}
		StringBuilder sb=new StringBuilder();
		for(String m:str) {
			sb.append(m.toString()+",");
		}
		return sb.substring(0,sb.length()-1);
	}
	
	//调试时输入的参数,复合对象直接用复合对象,数组就复制3份
	public List<ApiParameter> getDebugParams(){
		List<ApiParameter> list=new ArrayList();
		for(ApiParameter pa:this.params) {
			List<ApiParameter> chd=pa.getChildren();
			if(chd.size()>0) {
				list.addAll(chd);
				continue;
			}
			list.add(pa);
			if(pa.getClass().isArray()) {
				list.add(pa);
				list.add(pa);
			}
			
		}
		return list;
	}
	
	public List<ApiParameter> getReturnValue(){
		List list=new ArrayList();
		ApiParameter pa=result.getParams();
		//如果返回的是void,说明是直接返回页面
		if(pa.getName().equalsIgnoreCase("void")) {
			pa.setClazz(ModelAndView.class);
			pa.setDescription("/templates"+this.getUrl()+".html");
		}
		list.add(pa);
		return list;
	}
	
	public String getFullMethodName() {
		return this.fullName+"."+this.methodName;
	}
	
	//创建默认的josn格式的参数
	public String getJsonParam() {
		if(params.size()!=1) {
			throw new RuntimeException("此方法只支持参数只有1个的时候掉");
		}
		ApiParameter pa= params.get(0);
		Class clazz = pa.getClazz();
		if (ClassUtil.isInstance(clazz, Collection.class)) {
			if (pa.getType()!=null) {
				clazz = ClassUtil.getGenericClass(pa.getType());
			}
			Object o=ClassUtil.newInstance(clazz);
			List list=new ArrayList();
			list.add(o);
			return JsonUtil.NULL.toFormatString(list);
		}
		Object o=ClassUtil.newInstance(clazz);
		return JsonUtil.NULL.toFormatString(o);
		
	}
}
